import React, { useEffect, useState } from 'react'
import './address.css'
import { useNavigate } from 'react-router-dom';
import { NavBar, Cell, Popup, Button, Input, Form, Cascader, Switch, Tag   } from 'react-vant';
import { Edit } from '@react-vant/icons'
import options from './options'
import { AddressList, DefaultAddress, AddressAdd, AddressEdit } from '../../axios';
import { useSelector } from 'react-redux';
export default function Address() {
    let { userId } = useSelector(state => state.user)
    let [ addressList,setAddressList ] = useState([])
    let [ defaultAddress,setDefaultAddress ] = useState([])
    let [ title,setTitle ] = useState('')
    let [addressid,setAddressid] = useState('')
    let navigate = useNavigate()
    const [state, setState] = useState('')
    const [visible, setVisible] = useState(false)
    const onCancel = () => setVisible(false)
    useEffect(() => {
        // 地址列表
        SetAddressListv()
        // 默认地址
        SetDefaultAddress()
    },[])
    const SetAddressListv = () => {
      AddressList(userId).then(res => {
            // console.log(res);
            setAddressList(res.data.data)
        })
    }
    const SetDefaultAddress = () => {
        DefaultAddress({userid:userId}).then(res => {
            setDefaultAddress(res.data.data)
        })
    }
    const onClose = () => setState('')

    const [form] = Form.useForm()
    const onFinish = values => {
      let province = options.filter(item => item.value == values.area[0])
      let city = province[0].children.filter( item => item.value == values.area[1] )
      let county = city[0].children.filter( item => item.value == values.area[2] )
      
      // console.log(values,province[0].text,city[0].text,county[0].text)
      AddressAdd({...values,userid:userId,province:province[0].text,city:city[0].text,county:county[0].text}).then(res => {
        // console.log(res);
        if(res.data.code === '200'){
          console.log(1);
          onClose()
          SetAddressListv()
          SetDefaultAddress()
          form.resetFields()
        }
        
      })
    }
    const goedit = (values) => {
      setTitle('修改')
      setAddressid(values.addressid)

      let province = options.filter(item => item.text == values.province)
      let city = province[0].children.filter( item => item.text == values.city )
      let county = city[0].children.filter( item => item.text == values.county )
      // console.log(province[0].value,city[0].value,county[0].value);
      let area = [province[0].value,city[0].value,county[0].value]

      setState('bottom')
      form.setFieldsValue({
        name:values.name,
        tel:values.tel,
        addressDetail:values.addressDetail,
        isDefault:values.isDefault,
        area:area
      })
      

    }
    const gb = () => {
      onClose()
      form.resetFields()
    }
    const add = () => {
      setState('bottom')
      setTitle('添加')
    }
    const edit = () => {
      let values = form.getFieldsValue()
      let province = options.filter(item => item.value == values.area[0])
      let city = province[0].children.filter( item => item.value == values.area[1] )
      let county = city[0].children.filter( item => item.value == values.area[2] )
      AddressEdit({...values,userid:userId,province:province[0].text,city:city[0].text,county:county[0].text,addressid:addressid}).then(res => {
        if(res.data.code == '200'){
          onClose()
          form.resetFields()
          SetAddressListv()
          SetDefaultAddress()
        }
      })
      
      
    }
  return (
    <div className='ress-box'>
        <NavBar
        title="地址"
        leftText="返回"
        onClickLeft={() => navigate(-1)}
        />
        {addressList.length>0 && <ul>
          {
            addressList.map(item => {
              return <li className = 'address-li' key={item.addressid}>
                <input type="radio" name="show" id={item.addressid} />
                <div className='address-cen'>
                  <div className='address-top'>
                      <span className='address-top-left'>{item.name}</span>
                      <span>{item.tel}</span>
                      {defaultAddress.length > 0 && item.addressid == defaultAddress[0].addressid && <Tag color='red'
                      textColor='withe' round type="primary" className='address-tag'>默认</Tag>}
                    </div>
                    <div className='address-bot'>
                      {item.addressDetail}
                  </div>
                </div>
                <Edit onClick={() => goedit(item)} style={{fontSize:22}} />
              </li>
            })
          }
        </ul>}


        <div className='ress-tc-box'>
          <Cell className='ress-tc' title='新增地址' isLink onClick={add} />
        </div>
        
        <Popup
        visible={state === 'bottom'}
        position='bottom'
        onClose={onClose}
      >
         <Form
          form={form}
          
          onFinish={onFinish}
          footer={
            <div style={{ margin: '16px 16px 0' }}>
              {title==='添加'&&<Button round nativeType='submit' type='primary' block>
                保存
              </Button>}
              
            </div>
          }
        >
        <Form.Item
            name='name'
            label='姓名'
          >
            <Input placeholder='姓名' />
          </Form.Item>
          <Form.Item
            name='tel'
            label='电话'
          >
            <Input placeholder='电话' />
          </Form.Item>
          <Form.Item name='area' label='地区' isLink>
        <Cascader
          popup={{ round: true }}
          title='地区'
          options={options}
        >
          {(_, selectedRows, actions) => (
            <Input
              value={selectedRows.map(el => el.text).join(',')}
              readOnly
              placeholder='地区'
              onClick={() => actions.open()}
            />
          )}
        </Cascader>
      </Form.Item>

          <Form.Item
            name='addressDetail'
            label='详细地址'
          >
            <Input placeholder='详细地址' />
          </Form.Item>

          <Form.Item name='isDefault' label='默认收货地址' valuePropName='checked'>
            <Switch size={20} />
          </Form.Item>
        </Form>
        {title==='修改' && <Button onClick={edit} round nativeType='submit' type='primary' block>
                保存
          </Button>}
        <Button onClick={gb} style={{marginTop:'16px',marginBottom:'35px'}} round nativeType='submit' block>
                删除
        </Button>
      </Popup>
    </div>
  )
}
